import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { mergeConfig, type UserConfig } from 'vite';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import legacy from '@vitejs/plugin-legacy';
import UnoCSS from 'unocss/vite';
import prismjsPlugin from 'vite-plugin-prismjs-plus';

interface ConfigEnv {
  mode: string;
  ssrBuild?: boolean;
}

const __dirname = dirname(fileURLToPath(import.meta.url));

export default function viteConfig(defaultConfig: UserConfig, { mode, ssrBuild }: ConfigEnv) {
  return mergeConfig(defaultConfig, {
    plugins: [
      UnoCSS(),
      VueI18nPlugin({
        include: join(__dirname, '../common/locales/**'),
        ssr: true,
        dropMessageCompiler: true,
      }),
      legacy(),
      prismjsPlugin({
        manual: true,
        languages: [
          'markup',
          'javascript',
          'css',
          'php',
          'ruby',
          'python',
          'java',
          'c',
          'csharp',
          'cpp',
          'bash',
          'rust',
        ],
        plugins: [
          'line-numbers',
          'copy-to-clipboard',
        ],
        css: true,
      }),
    ],
    css: {
      postcss: __dirname,
    },
    build: {
      cssTarget: 'chrome61',
      rollupOptions: {
        output: {
          manualChunks: ssrBuild ? undefined : (id: string) => {
            const deps: Record<string, string[]> = {
              vue: ['vue', 'vue-router', 'pinia', 'vue-i18n', '@vueuse/core'],
              'markdown-it': ['markdown-it'],
              'ark-ui': ['@ark-ui'],
              prismjs: ['prismjs'],
              vendors: ['lazysizes', 'lodash-es', 'axios', 'scrollama', 'countup.js', 'date-fns'],
            };

            for (const key in deps) {
              if (deps[key].some(dep => id.includes(`/node_modules/${dep}/`))) {
                return key;
              }
            }

            const chunks: Record<string, string[]> = {
              locales: ['/common/locales/'],
              prismjs: ['virtual:prismjs'],
            };

            for (const key in chunks) {
              if (chunks[key].some(chunk => id.includes(chunk))) {
                return key;
              }
            }
          },
        },
      },
    },
    ssr: {
      noExternal: mode === 'build' && ssrBuild ?
        [
          'countup.js',
        ]
        :
        [
          'countup.js',
        ],
    },
  });
}
